<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
 *
 * functions.php template file
 *
 * (c) 2009 by Mike Walsh
 *
 * @author Mike Walsh <mike_walsh@mindspring.com>
 * @package sandbox-swimteam
 * @subpackage Sandbox
 * @version $Revision$
 * @lastmodified $Author$
 * @lastmodifiedby $Date$
 *
 */

//  Sandbox issues a PHP warning, the @ sign suppresses it.
require("sandbox-patch/functions.php") ;

//  The TEMPLATEPATH constant can't be used for child
//  themes as it returns the parent theme path so we
//  need to figure out what SBLTTHEMEPATH is ...

define("SBLTHEMEPATH", sprintf("/%s/themes/%s",
    basename(WP_CONTENT_DIR), basename(dirname(__FILE__)))) ;

//  Define constants to drive the theme options page.
//  These values are important and should not be changed
//  as they drive the selection of the proper header
//  image and CSS file.

define('SBST_THEME_BG_IMAGE_SMALL', 'small') ;
define('SBST_THEME_BG_IMAGE_LARGE', 'large') ;
define('SBST_THEME_DEFAULT_BG_IMAGE_SIZE', SBST_THEME_BG_IMAGE_SMALL) ;

define('SBST_THEME_COLOR_SCHEME_BLUE', 'blue') ;
define('SBST_THEME_COLOR_SCHEME_DKBLUE', 'dkblue') ;
define('SBST_THEME_COLOR_SCHEME_GREEN', 'green') ;
define('SBST_THEME_COLOR_SCHEME_LTBLUE', 'ltblue') ;
define('SBST_THEME_COLOR_SCHEME_ORANGE', 'orange') ;
define('SBST_THEME_COLOR_SCHEME_PURPLE', 'purple') ;
define('SBST_THEME_COLOR_SCHEME_RED', 'red') ;
define('SBST_THEME_COLOR_SCHEME_WHITE', 'white') ;
define('SBST_THEME_COLOR_SCHEME_YELLOW', 'yellow') ;
define('SBST_THEME_DEFAULT_COLOR_SCHEME', SBST_THEME_COLOR_SCHEME_RED) ;

define('SBST_THEME_BG_IMAGE', '%s/images/background/seamless-water-pattern-%s-%s.png') ;
define('SBST_THEME_BG_IMAGE_DISPLAY_WIDTH', "400px") ;
define('SBST_THEME_BG_IMAGE_DISPLAY_HEIGHT', "100px") ;

define('SBST_THEME_OPTION_HIL', 'sbstlfthdrimg') ;
define('SBST_THEME_OPTION_HIC', 'sbstctrhdrimg') ;
define('SBST_THEME_OPTION_HIR', 'sbstrghthdrimg') ;
define('SBST_THEME_OPTION_LOGIN', 'sbstloginhdrimg') ;
define('SBST_THEME_OPTION_HIL_CSS', 'sbstlfthdrimgcss') ;
define('SBST_THEME_OPTION_HIC_CSS', 'sbstctrhdrimgcss') ;
define('SBST_THEME_OPTION_HIR_CSS', 'sbstrghthdrimgcss') ;
define('SBST_THEME_OPTION_LOGIN_CSS', 'sbstloginhdrimgcss') ;
define('SBST_THEME_OPTION_COLOR_SCHEME', 'sbstclrschm') ;
define('SBST_THEME_OPTION_BLOG_TITLE_CSS', 'sbsttitlcss') ;
define('SBST_THEME_OPTION_BLOG_TAGLINE_CSS', 'sbsttaglincss') ;

//  Default theme options

define('SBST_THEME_OPTION_HIL_DEFAULT', '') ;
define('SBST_THEME_OPTION_HIC_DEFAULT', '') ;
define('SBST_THEME_OPTION_HIR_DEFAULT', '') ;
define('SBST_THEME_OPTION_LOGIN_DEFAULT', '') ;
define('SBST_THEME_OPTION_HIL_CSS_DEFAULT', '') ;
define('SBST_THEME_OPTION_HIC_CSS_DEFAULT', '') ;
define('SBST_THEME_OPTION_HIR_CSS_DEFAULT', '') ;
define('SBST_THEME_OPTION_LOGIN_CSS_DEFAULT', '') ;
define('SBST_THEME_OPTION_COLOR_SCHEME_DEFAULT',
    SBST_THEME_BG_IMAGE_SMALL . ":" . SBST_THEME_COLOR_SCHEME_RED) ;
define('SBST_THEME_OPTION_BLOG_TITLE_CSS_DEFAULT', '') ;
define('SBST_THEME_OPTION_BLOG_TAGLINE_CSS_DEFAULT', '') ;

/**
 * Enqueue any external libraries and CSS needed to support admin options.
 *
 * @return - void
 */
function sbst_theme_enqueue_admin()
{
    //  Reuqest the shipping version of jQuery be loaded
    //  as it is necessary to support the SuperFish menus.

    wp_enqueue_script('jquery') ;
    wp_enqueue_script('jquery-ui-core') ;
    wp_enqueue_script('jquery-ui-draggable') ;
    wp_enqueue_script('jquery-ui-droppable') ;
    wp_enqueue_script('jquery-ui-accordion', false, array('jquery',
        'jquery-ui-core', 'jquery-ui-draggable', 'jquery-ui-droppable')) ;

    //  Load jQuery UI Accordion

    //  Need the jQuery UI CSS - load it from Google's CDN

    wp_enqueue_style('jquery-style',
        'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css') ;
}

/**
 * Enqueue any external libraries and CSS needed to support theme.
 *
 * @return - void
 */
function sbst_theme_enqueue()
{
    //  Reuqest the shipping version of jQuery be loaded
    //  as it is necessary to support the SuperFish menus.

    wp_enqueue_script('jquery') ;

    //  Load Superfish menus - it comes from within the theme

    $superfish = "%s/js/superfish-1.4.8/js/superfish.js" ;
    $hoverIntent = "%s/js/superfish-1.4.8/js/hoverIntent.js" ;
    $sfmenu = "%s/js/sf-menu.js" ;

    wp_enqueue_script('hoverIntent',
        sprintf($hoverIntent, SBLTHEMEPATH), array('jquery')) ;
    wp_enqueue_script('superfish',
        sprintf($superfish, SBLTHEMEPATH), array('jquery')) ;
    wp_enqueue_script('sfmenu',
        sprintf($sfmenu, SBLTHEMEPATH), array('jquery')) ;

    //  Load the CSS based on the theme options

    $theme_url = get_stylesheet_directory_uri() ;

    $theme_options = sbst_theme_get_options() ;
    list($size, $color) = explode(":", $theme_options[SBST_THEME_OPTION_COLOR_SCHEME]) ;

    $superfish_css = sprintf("%s/css/superfish-%s.css",
        $theme_url, strtolower($color)) ;

    $bg_image_size_css = sprintf("%s/css/sandbox-swimteam-bg-%s-%s.css", $theme_url,
        strtolower($size), strtolower($color)) ;

    $color_scheme_css = sprintf("%s/css/sandbox-swimteam-%s.css",
        $theme_url, strtolower($color)) ;

    wp_register_style('superfishcss', $superfish_css) ; 
    wp_enqueue_style( 'superfishcss') ;

    wp_register_style('sandbox-swimteam-bg_image_size', $bg_image_size_css) ; 
    wp_enqueue_style( 'sandbox-swimteam-bg_image_size') ;

    wp_register_style('sandbox-swimteam-color', $color_scheme_css) ; 
    wp_enqueue_style( 'sandbox-swimteam-color') ;
}

//  Hook in a redirect action for the template to the enqueue will run

add_action('template_redirect','sbst_theme_enqueue');

/**
 * filter to add a theme footer
 *
 */
function sbst_theme_footer()
{
    printf("Copyright &copy; 2007-%s, %s - All rights reserved.",
        date('Y'), get_bloginfo('blogtitle')) ;
}

//  Hook in a action for the template to the enqueue will run

add_action('wp_footer','sbst_theme_footer');

//  Set up theme options - allows theme
//  to be configured with a color scheme
//  and Fibblesnork background images.

add_action('admin_menu', 'sbst_theme_options_page');

/**
 * Sandbox Swim Team Theme options page hook
 */
function sbst_theme_options_page()
{
    add_theme_page('sbst', 'Theme Options',
        'manage_options', 'functions', 'sbst_theme_set_options');
}

/**
 * Returns the default theme options.
 *
 * @since Sandbox-SwimTeam 3.0
 */
function sbst_get_default_theme_options()
{
	$default_theme_options = array(
        SBST_THEME_OPTION_HIL => SBST_THEME_OPTION_HIL_DEFAULT
       ,SBST_THEME_OPTION_HIC => SBST_THEME_OPTION_HIC_DEFAULT
       ,SBST_THEME_OPTION_HIR => SBST_THEME_OPTION_HIR_DEFAULT
       ,SBST_THEME_OPTION_LOGIN => SBST_THEME_OPTION_LOGIN_DEFAULT
       ,SBST_THEME_OPTION_HIL_CSS => SBST_THEME_OPTION_HIL_CSS_DEFAULT
       ,SBST_THEME_OPTION_HIC_CSS => SBST_THEME_OPTION_HIC_CSS_DEFAULT
       ,SBST_THEME_OPTION_HIR_CSS => SBST_THEME_OPTION_HIR_CSS_DEFAULT
       ,SBST_THEME_OPTION_LOGIN_CSS => SBST_THEME_OPTION_LOGIN_CSS_DEFAULT
       ,SBST_THEME_OPTION_COLOR_SCHEME => SBST_THEME_OPTION_COLOR_SCHEME_DEFAULT
       ,SBST_THEME_OPTION_BLOG_TITLE_CSS => SBST_THEME_OPTION_BLOG_TITLE_CSS_DEFAULT
       ,SBST_THEME_OPTION_BLOG_TAGLINE_CSS => SBST_THEME_OPTION_BLOG_TAGLINE_CSS_DEFAULT
	) ;

	return apply_filters('sbst_default_theme_options', $default_theme_options) ;
}

/**
 * Returns the options array for the Sandbox SwimTeam theme.
 *
 * @since Sandbox-SwimTeam 3.0
 */
function sbst_theme_get_options()
{
    //  Get the default options in case anything new has been added
    $default_options = sbst_get_default_theme_options() ;

    //  If there is nothing persistent saved, return the default

    if (get_option('sbst_options') === false)
        return $default_options ;

    //  One of the issues with simply merging the defaults is that by
    //  using checkboxes (which is the correct UI decision) WordPress does
    //  not save anything for the fields which are unchecked which then
    //  causes wp_parse_args() to incorrectly pick up the defaults.
    //  Since the array keys are used to build the form, we need for them
    //  to "exist" so if they don't, they are created and set to null.

    $theme_options = get_option('sbst_options', $default_options) ;

    foreach ($default_options as $key => $value)
    {
        if (!array_key_exists($key, $theme_options))
            $theme_options[$key] = null ;
    }

    return $theme_options ;
}

/**
 * Build Header Image Drag and Drop
 *
 * @param $filler - string - filler to add to ids and classes.
 */
function sbst_header_image_drag_n_drop($filler)
{
    $thumbnail_scale = 0.67 ;
    $thumbnail_width = get_option('thumbnail_size_w') * $thumbnail_scale ;
    $thumbnail_height = get_option('thumbnail_size_h') * $thumbnail_scale ;
 
    //  Build the drag zone - don't include the existing image if set

    printf("<div class=\"demo ui-widget ui-helper-clearfix\">\n") ;

    printf("<ul id=\"sbst%shdrgallery\" class=\"gallery ui-helper-reset ui-helper-clearfix\">\n", $filler) ;

    $images = &get_children('post_type=attachment&post_mime_type=image') ;

    if (!empty($images)) {
    foreach ( $images as $attachment_id => $attachment )
    {
        $thumb = wp_get_attachment_image_src($attachment_id) ;
        $image = wp_get_attachment_image_src($attachment_id, 'full') ;

        printf("<li id=\"sbst%shdrimg-%s\" class=\"ui-widget-content ui-corner-tr\">\n", $filler, $attachment_id) ;
        printf("<h5 class=\"ui-widget-header\">%sx%s</h5>\n", $image[1], $image[2]) ;
        printf("<img src=\"%s\" width=\"%s\" height=\"%s\" alt=\"%s\"/>\n", $thumb[0], $thumbnail_width, $thumbnail_height, basename($image[0])) ;
   
        printf("<a href=\"%s\" title=\"%s\" class=\"ui-icon ui-icon-zoomin\">View larger</a>\n", $image[0], basename($image[0])) ;
        printf("<a href=\"%s\" title=\"Select Image\" class=\"ui-icon ui-icon-check\">Remove Image</a>\n</li>\n", $image[0]) ;
    }
    }

    //  Build the drop zone and handle exisitng image if set

    printf("</ul><div id=\"sbst%shdrimg\" class=\"ui-widget-content ui-state-default\">\n", $filler) ;
    printf("<h4 class=\"ui-widget-header\"><span class=\"ui-icon ui-icon-check\">Left Header Image</span>Image</h4>\n</div>\n");

    printf("</div><!-- End DnD block -->\n") ;
}

/**
 * sbst theme options page form
 *
 */
function sbst_theme_set_options()
{
    $theme_options = sbst_theme_get_options() ;

    //print_r($theme_options) ;

    $sbst_theme_bg_image_size_options = array(
        SBST_THEME_BG_IMAGE_SMALL => SBST_THEME_BG_IMAGE_SMALL
       ,SBST_THEME_BG_IMAGE_LARGE => SBST_THEME_BG_IMAGE_LARGE
   ) ;

    $sbst_theme_color_scheme_options = array(
        SBST_THEME_COLOR_SCHEME_BLUE => SBST_THEME_COLOR_SCHEME_BLUE
       //,SBST_THEME_COLOR_SCHEME_DKBLUE => SBST_THEME_COLOR_SCHEME_DKBLUE
       ,SBST_THEME_COLOR_SCHEME_GREEN => SBST_THEME_COLOR_SCHEME_GREEN
       //,SBST_THEME_COLOR_SCHEME_LTBLUE => SBST_THEME_COLOR_SCHEME_LTBLUE
       ,SBST_THEME_COLOR_SCHEME_ORANGE => SBST_THEME_COLOR_SCHEME_ORANGE
       //,SBST_THEME_COLOR_SCHEME_PURPLE => SBST_THEME_COLOR_SCHEME_PURPLE
       ,SBST_THEME_COLOR_SCHEME_RED => SBST_THEME_COLOR_SCHEME_RED
       //,SBST_THEME_COLOR_SCHEME_WHITE => SBST_THEME_COLOR_SCHEME_WHITE
       ,SBST_THEME_COLOR_SCHEME_YELLOW => SBST_THEME_COLOR_SCHEME_YELLOW
   ) ;

    $sbst_theme_thumbnails = array() ;

    foreach ($sbst_theme_bg_image_size_options as $bg_image_size)
    {
        $url = get_stylesheet_directory_uri() ;

        foreach ($sbst_theme_color_scheme_options as $color)
        {
            $img = sprintf(SBST_THEME_BG_IMAGE, $url, $color, $bg_image_size) ;
            $key = sprintf("%s:%s", ucwords($bg_image_size), ucwords($color)) ;
            $sbst_theme_thumbnails[$key] = $img ;
        }
    }

    //  Default thumbnails are big, add a scaling factor which
    //  will become an theme option setting in the future.

    $thumbnail_scale = 0.67 ;
    $thumbnail_width = get_option('thumbnail_size_w') * $thumbnail_scale ;
    $thumbnail_height = get_option('thumbnail_size_h') * $thumbnail_scale ;

?>
<div class="wrap">

<style type="text/css">
/* Drag and Drop */
#droppable, #header-image-left, #header-image-center, #header-image-right { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
.draggable-image, #draggable, #draggable-nonvalid { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }

/* Gallery Control */
.gallery.custom-state-active { background: #eee; }
.gallery li { float: left; width: <?php echo $thumbnail_width . "px"?>; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; }
.gallery li h5 { margin: 0 0 0.4em; cursor: move; }
.gallery li a { float: right; }
.gallery li a.ui-icon-zoomin { float: left; }
.gallery li img { width: 100%; cursor: move; }

/* Left Header Image */
#sbstlfthdrgallery { float: left; width: 75%; min-height: 12em; } * html #sbstlfthdrgallery { height: 12em; } /* IE6 */
#sbstlfthdrimg { float: right; width: 20%; min-height: 12em; padding: 1%; text-align: center; margin: 0 auto;} * html #sbstlfthdrimg { height: 18em; } /* IE6 */
#sbstlfthdrimg h4 { line-height: 20px; margin: 0 0 0.4em; }
#sbstlfthdrimg h4 .ui-icon { float: left; }
#sbstlfthdrimg .gallery h5 { display: none; }

/* Center Header Image */
#sbstctrhdrgallery { float: left; width: 75%; min-height: 12em; } * html #sbstctrhdrgallery { height: 12em; } /* IE6 */
#sbstctrhdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #sbstctrhdrimg { height: 18em; } /* IE6 */
#sbstctrhdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#sbstctrhdrimg h4 .ui-icon { float: left; }
#sbstctrhdrimg .gallery h5 { display: none; }

/* Right Header Image */
#sbstrghthdrgallery { float: left; width: 75%; min-height: 12em; } * html #sbstrghthdrgallery { height: 12em; } /* IE6 */
#sbstrghthdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #sbstrghthdrimg { height: 18em; } /* IE6 */
#sbstrghthdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#sbstrghthdrimg h4 .ui-icon { float: left; }
#sbstrghthdrimg .gallery h5 { display: none; }

/* Login Image */
#sbstloginhdrgallery { float: left; width: 75%; min-height: 12em; } * html #sbstloginhdrgallery { height: 12em; } /* IE6 */
#sbstloginhdrimg { float: right; width: 20%; min-height: 15em; padding: 1%;} * html #sbstloginhdrimg { height: 18em; } /* IE6 */
#sbstloginhdrimg h4 { line-height: 16px; margin: 0 0 0.4em; }
#sbstloginhdrimg h4 .ui-icon { float: left; }
#sbstloginhdrimg .gallery h5 { display: none; }

</style>

<br clear="all"/>

    <div id="icon-options-general" class="icon32"><br /></div>
    <h2>Sandbox Swim Team Theme Options</h2>
    <form name="sbst_theme_options" method="post" action="options.php">
    <<?php settings_fields('sbst_options') ; ?>
    <div id="options-accordion">
        <div><h3><a href="#">Left Header Image</a></h3>
            <?php sbst_header_image_drag_n_drop("lft") ; ?>
        </div>
        <div><h3><a href="#">Center Header Image</a></h3>
            <?php sbst_header_image_drag_n_drop("ctr") ; ?>
        </div>
        <div><h3><a href="#">Right Header Image</a></h3>
            <?php sbst_header_image_drag_n_drop("rght") ; ?>
        </div>
        <div><h3><a href="#">Login Image</a></h3>
            <?php sbst_header_image_drag_n_drop("login") ; ?>
        </div>
        <div><h3><a href="#">CSS Overrides</a></h3>
            <div>
                <h4>Blog Title</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_BLOG_TITLE_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_BLOG_TITLE_CSS] ?>"/>
                <h4>Blog Tagline</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_BLOG_TAGLINE_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_BLOG_TAGLINE_CSS] ?>"/>
                <h4>Left Header Image Block</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_HIL_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIL_CSS] ?>"/>
                <h4>Center Header Image Block</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_HIC_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIC_CSS] ?>"/>
                <h4>Right Header Image Block</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_HIR_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIR_CSS] ?>"/>
                <h4>Login Page Image Block</h4>
                <input size="60" type="text" name="sbst_options[<?php echo SBST_THEME_OPTION_LOGIN_CSS; ?>]" value="<?php echo $theme_options[SBST_THEME_OPTION_LOGIN_CSS] ?>"/>
            </div>
        </div>
            <div>
                <h3><a href="#">Theme Color Scheme</a></h3>
                <div>
<table class="widefat fixed" style="margin: 10px 0px;" cellspacing="0">
<!--
    <thead>
    <tr>

    <th scope="col" id="rb" class="manage-column column-rb check-column" style="">&nbsp;</th>
    <th scope="col" id="icon" class="manage-column column-icon" style=""></th>
    <th scope="col" id="media" class="manage-column column-media" style="">File</th>
    <th scope="col" id="width" class="manage-column column-size" style="">Size</th>
    <th scope="col" id="height" class="manage-column column-scheme" style="">Color Scheme</th>


    </tr>
    </thead>

    <tfoot>
    <tr>

    <th scope="col" id="rb" class="manage-column column-rb check-column" style="">&nbsp;</th>
    <th scope="col" id="icon" class="manage-column column-icon" style=""></th>
    <th scope="col" id="media" class="manage-column column-media" style="">File</th>
    <th scope="col" id="width" class="manage-column column-size" style="">Size</th>
    <th scope="col" id="height" class="manage-column column-scheme" style="">Color Scheme</th>
    </tr>
    </tfoot>

-->
    <tbody id="the-list" class="list:post">
<?php
    $tdctr = 0 ;
    $priorSize = null ;

    foreach ($sbst_theme_thumbnails as $key => $value)
    {
        $checked = (strtolower($key) == $theme_options[SBST_THEME_OPTION_COLOR_SCHEME]) ? " checked=\"checked\"" : "" ;

        list($size, $color) = explode(":", $key) ;

        //  New row?  If so, open the row.
        if (($tdctr == 0) || ((strtolower($size) == SBST_THEME_BG_IMAGE_LARGE)
            && ($priorSize == SBST_THEME_BG_IMAGE_SMALL)))
        {
            $tdctr = 0 ;
            print "<tr valign=\"middle\">" ;
        }

        $priorSize = strtolower($size) ;

        printf("<td style=\"padding: 10px 5px;\" align=\"center\"><img src=\"%s\" alt=\"%s\"><br/>", $value, basename($value)) ;
        printf("<input type='radio' name='sbst_options[%s]' value=\"%s\"%s /><br/>", SBST_THEME_OPTION_COLOR_SCHEME, strtolower($key), $checked) ;
        printf("<strong>%s<br/>%s</strong></td>", $size, $color) ;

        //  End the row after 3 columns
        if (++$tdctr == 2)
        {
            $tdctr = 0 ;
            print "</tr>" ;
        }
    }

    //  Partial row?
    if ($tdctr != 2) print "</tr>" ;
?>
    </tbody>
</table>
</div>
            </div>
        </div>
        <br/>

  <input type="hidden" name="sbst_options[sbstlfthdrimg]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIL]; ?>" />
  <input type="hidden" name="sbst_options[sbstctrhdrimg]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIC]; ?>" />
  <input type="hidden" name="sbst_options[sbstrghthdrimg]" value="<?php echo $theme_options[SBST_THEME_OPTION_HIR]; ?>" />
  <input type="hidden" name="sbst_options[sbstloginhdrimg]" value="<?php echo $theme_options[SBST_THEME_OPTION_LOGIN]; ?>" />
  <input type="submit" name="Submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
  </form>
  </div>

<script type="text/javascript">

//
//  This jQuery/jQuery UI code was derived from the
//  jQuery UI Simple Photo Manager Example found at:
//
//  http://jqueryui.com/demos/droppable/#photo-manager
//
//  This Javascript allows the user to select images from
//  the media library to be used in the thene header using
//  a drag and drop implementation.
//

jQuery(document).ready(function($) {
    //  Set up the accordion and set the first section to be open
    $("#options-accordion").accordion({header: "h3", active: 0, autoHeight: true});

    // set up the left header image gallery and container
    var $sbstlfthdrcntr = false ;
    var $sbstlfthdrimg = $('#sbstlfthdrimg');
    var $sbstlfthdrgallery = $('#sbstlfthdrgallery');

    // set up the center header image gallery and container
    var $sbstctrhdrcntr = false ;
    var $sbstctrhdrimg = $('#sbstctrhdrimg');
    var $sbstctrhdrgallery = $('#sbstctrhdrgallery');

    // set up the right header image gallery and container
    var $sbstrghthdrcntr = false ;
    var $sbstrghthdrimg = $('#sbstrghthdrimg');
    var $sbstrghthdrgallery = $('#sbstrghthdrgallery');

    // set up the login image gallery and container
    var $sbstloginhdrcntr = false ;
    var $sbstloginhdrimg = $('#sbstloginhdrimg');
    var $sbstloginhdrgallery = $('#sbstloginhdrgallery');

    // let the left header gallery items be draggable
    $('li',$sbstlfthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the left header image be droppable, accepting the gallery items
    $sbstlfthdrimg.droppable({
        accept: '#sbstlfthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the left gallery be droppable as well,
    // accepting items from the left header image
    $sbstlfthdrgallery.droppable({
        accept: '#sbstlfthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center header gallery items be draggable
    $('li',$sbstctrhdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
        });

    // let the center header image be droppable,
    // accepting the gallery items
    $sbstctrhdrimg.droppable({
        accept: '#sbstctrhdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the center gallery be droppable as well,
    // accepting items from the left header image
    $sbstctrhdrgallery.droppable({
        accept: '#sbstctrhdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // let the right header gallery items be draggable
    $('li',$sbstrghthdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the right header image be droppable,
    // accepting the gallery items
    $sbstrghthdrimg.droppable({
        accept: '#sbstrghthdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the right gallery be droppable as well,
    // accepting items from the left header image
    $sbstrghthdrgallery.droppable({
        accept: '#sbstrghthdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // let the login gallery items be draggable
    $('li',$sbstloginhdrgallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the login image be droppable,
    // accepting the gallery items
    $sbstloginhdrimg.droppable({
        accept: '#sbstloginhdrgallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            selectImage(ui.draggable, ui.draggable.attr('id'));
        }
    });

    // let the login gallery be droppable as well,
    // accepting items from the left header image
    $sbstloginhdrgallery.droppable({
        accept: '#sbstloginhdrimg li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // image deletion function
    var recycle_icon = '<a href="#" title="Remove Image" class="ui-icon ui-icon-trash">Remove Image</a>';

    function selectImage($item, $attrid) {
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;

        switch (galleryId)
        {
            case "sbstlfthdrimg" :
                hdrimg = $sbstlfthdrimg;
                break;
 
            case "sbstctrhdrimg" :
                hdrimg = $sbstctrhdrimg;
                break;
 
            case "sbstrghthdrimg" :
                hdrimg = $sbstrghthdrimg;
                break;
 
            case "sbstloginhdrimg" :
                hdrimg = $sbstloginhdrimg;
                break;
        }
 
        $item.fadeOut(function() {
            var $list = $('ul',hdrimg).length ? $('ul',hdrimg) : $('<ul class="gallery ui-helper-reset"/>').appendTo(hdrimg);

            $item.find('a.ui-icon-check').remove();
            $item.append(recycle_icon).appendTo($list).fadeIn(function() {
                $item.animate({ width: '<?php echo $thumbnail_width . "px" ?>' }).find('img').animate({ height: '<?php echo $thumbnail_height . "px" ?>' });
        return ;
            });
        });

        hdrimg.droppable('disable');

        switch (galleryId)
        {
            case "sbstlfthdrimg" :
                $sbstlfthdrcntr = true ;
                break;
 
            case "sbstctrhdrimg" :
                $sbstctrhdrcntr = true;
                break;
 
            case "sbstrghthdrimg" :
                $sbstrghthdrcntr = true;
                break;
 
            case "sbstloginhdrimg" :
                $sbstloginhdrcntr = true;
                break;
        }
 
        // Save it in the hidden input
        $("input[name='sbst_options[" + galleryId + "]']").val(imageId);
    }

    // image recycle function
    var trash_icon = '<a href="#" title="Select Image" class="ui-icon ui-icon-check">Select Image</a>';
    function removeImage($item, $attrid) {
        // Find numeric id of header image
        var imageId = $attrid.replace(/[^0-9]/gi,'')/1;
        var galleryId = $attrid.split("-", 2)[0];

        var hdrimg = null;
        var hdrgallery = null;

        switch (galleryId)
        {
            case "sbstlfthdrimg" :
                hdrimg = $sbstlfthdrimg;
                hdrgallery = $sbstlfthdrgallery;
                break;
 
            case "sbstctrhdrimg" :
                hdrimg = $sbstctrhdrimg;
                hdrgallery = $sbstctrhdrgallery;
                break;
 
            case "sbstrghthdrimg" :
                hdrimg = $sbstrghthdrimg;
                hdrgallery = $sbstrghthdrgallery;
                break;
 
            case "sbstloginhdrimg" :
                hdrimg = $sbstloginhdrimg;
                hdrgallery = $sbstloginhdrgallery;
                break;
        }
 
        $item.fadeOut(function() {
            $item.find('a.ui-icon-trash').remove();
            $item.css('width','<?php echo $thumbnail_width . "px" ?>').append(trash_icon).find('img').css('height','<?php echo $thumbnail_height . "px" ?>').end().appendTo(hdrgallery).fadeIn();
        });

        hdrimg.droppable('enable');

        switch (galleryId)
        {
            case "sbstlfthdrimg" :
                $sbstlfthdrcntr = false;
                break;
 
            case "sbstctrhdrimg" :
                $sbstctrhdrcntr = false;
                break;
 
            case "sbstrghthdrimg" :
                $sbstrghthdrcntr = false;
                break;
 
            case "sbstloginhdrimg" :
                $sbstloginhdrcntr = false;
                break;
        }
 
        $("input[name='sbst_options[" + galleryId + "]']").val("");
    }

    // image preview function, demonstrating the ui.dialog used as a modal window
    function viewLargerImage($link) {
        var src = $link.attr('href');
        var title = $link.siblings('img').attr('alt');
        var $modal = $('img[src$="'+src+'"]');

        if ($modal.length) {
            $modal.dialog('open')
        } else {
            var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />').attr('src',src).appendTo('body');
            setTimeout(function() {
                img.dialog({
                    title: title,
                    width: 400,
                    modal: true
                });
            }, 1);
        }
    }

    // resolve the icons behavior with event delegation
    $('ul.gallery > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);

        var hdrcntr = null;
        var gallery = $item.attr('id').split("-", 2)[0];

        switch (gallery)
        {
            case "sbstlfthdrimg" :
                hdrcntr = $sbstlfthdrcntr;
                break;
 
            case "sbstctrhdrimg" :
                hdrcntr = $sbstctrhdrcntr;
                break;
 
            case "sbstrghthdrimg" :
                hdrcntr = $sbstrghthdrcntr;
                break;
        }

        if ($target.is('a.ui-icon-check')) {
            if (hdrcntr) {
                $item.fadeOut('slow', function() {
                    //$item.appendTo($sbstlfthdrgallery);
                }) ;
                $item.fadeIn('slow') ;
            }
            else {
                selectImage($item, $item.attr('id'));
            }
        } else if ($target.is('a.ui-icon-zoomin')) {
            viewLargerImage($target);
            } else if ($target.is('a.ui-icon-trash')) {
            removeImage($item, $item.attr('id'));
        }

        return false;
    });


    //  Preload header images?  Need to move any images
    //  that are already set as one of the header images.
 
    //  Left header image preload?
    if ($("input[name='sbst_options[sbstlfthdrimg]']").val() != "") {
        selectImage($("#sbstlfthdrimg-" +
            $("input[name='sbst_options[sbstlfthdrimg]']").val()), "sbstlfthdrimg-" +
            $("input[name='sbst_options[sbstlfthdrimg]']").val()) ;
    }

    //  Center header image preload?
    if ($("input[name='sbst_options[sbstctrhdrimg]']").val() != "") {
        selectImage($("#sbstctrhdrimg-" +
            $("input[name='sbst_options[sbstctrhdrimg]']").val()), "sbstctrhdrimg-" +
            $("input[name='sbst_options[sbstctrhdrimg]']").val()) ;
    }

    //  Right header image preload?
    if ($("input[name='sbst_options[sbstrghthdrimg]']").val() != "") {
        selectImage($("#sbstrghthdrimg-" +
            $("input[name='sbst_options[sbstrghthdrimg]']").val()), "sbstrghthdrimg-" +
            $("input[name='sbst_options[sbstrghthdrimg]']").val()) ;
    }

    //  Login page image preload?
    if ($("input[name='sbst_options[sbstloginhdrimg]']").val() != "") {
        selectImage($("#sbstloginhdrimg-" +
            $("input[name='sbst_options[sbstloginhdrimg]']").val()), "sbstloginhdrimg-" +
            $("input[name='sbst_options[sbstloginhdrimg]']").val()) ;
    }
});
</script>    

<?php
}

/**
 * sbst_admin_init()
 *
 * Init actions for the Dashboard interface.
 *
 * @return null
 */
function sbst_admin_init()
{
    sbst_theme_enqueue_admin() ;
    register_setting('sbst_options', 'sbst_options') ;
}

add_action('admin_init', 'sbst_admin_init') ;

/**
 * Custom Login Screen
 *
 */
function custom_login()
{ 
    $theme_options = sbst_theme_get_options() ;
    $theme_url = get_stylesheet_directory_uri() ;

    list($size, $color) = explode(":", $theme_options[SBST_THEME_OPTION_COLOR_SCHEME]) ;

    $bg_image_size_css = sprintf("%s/css/sandbox-swimteam-bg-%s-%s.css", $theme_url,
        strtolower($size), strtolower($color)) ;

    $color_scheme_css = sprintf("%s/css/sandbox-swimteam-%s.css",
        $theme_url, strtolower($color)) ;

    printf("<link rel=\"stylesheet\" type=\"text/css\" href=\"%s/css/sandbox-swimteam-login-%s.css\" />\n", get_stylesheet_directory_uri(), $color) ;
    printf("<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\" />\n", $bg_image_size_css) ;
 
    //  Login page image

    $style = $theme_options[SBST_THEME_OPTION_LOGIN_CSS] ; 

    if (!empty($theme_options[SBST_THEME_OPTION_LOGIN]))
    {
        error_log(sprintf('%s::%s', basename(__FILE__), __LINE__)) ;
        $loginimg = wp_get_attachment_image_src($theme_options[SBST_THEME_OPTION_LOGIN], 'full') ;
        print "<style type='text/css'>\n" ;
        print ".login h1 a {\n" ;
        print "    display: block;\n" ;
	    //print "    margin-left: auto;\n" ;
	    //print "    margin-right: auto;\n" ;
	    print "    margin: 0px auto 20px auto;\n" ;
	    printf("    min-width: %spx !important;\n", $loginimg[1]) ;
	    printf("    min-height: %spx !important;\n", $loginimg[2]) ;
        printf("    background: url(%s) 50%s 100%s no-repeat;\n", $loginimg[0], "%", "%") ;
        $overrides = explode(';', $style) ;
        foreach ($overrides as $override)
            printf("    %s;\n", trim($override)) ;
        print  "</style>\n" ;
    }
}
add_action('login_head', 'custom_login');

// Widgets plugin: intializes the plugin after the widgets above have passed snuff
function sbst_theme_widgets_init() {
	if ( !function_exists('register_sidebar') )
		return;

	// Formats the Swim Team Theme widgets, adding readability-improving whitespace
	$p = array(
        'name'           =>   null,
		'before_widget'  =>   "\n\t\t\t" . '<li id="%1$s" class="widget %2$s">',
		'after_widget'   =>   "\n\t\t\t</li>\n",
		'before_title'   =>   "\n\t\t\t\t". '<h3 class="widgettitle">',
		'after_title'    =>   "</h3>\n"
	);

    //  Unregister the sidebars that the Sandbox theme defines

    unregister_sidebar('sidebar-1') ;
    unregister_sidebar('sidebar-2') ;

    //  Build four new sidebars - they are aranged where the
    //  North spans two columns, East and West each occupy one
    //  column, and South spans two columns.

    $p['name'] = "North Sidebar";
    register_sidebar($p) ;

    $p['name'] = "West Sidebar";
    register_sidebar($p) ;

    $p['name'] = "East Sidebar";
    register_sidebar($p) ;

    $p['name'] = "South Sidebar";
    register_sidebar($p) ;

    //  Define new sidebars that  span the header and footer

    $p['name'] = "Header Sidebar";
    register_sidebar($p) ;

    $p['name'] = "Footer Sidebar";
    register_sidebar($p) ;

    $p['name'] = "Sponsor Sidebar";
    register_sidebar($p) ;
}

/**
 * Register Navigation Menus
 *
 */
function sbst_register_nav_menu()
{
	register_nav_menu( 'primary-menu', __( 'Primary Menu' ) );
}

/**
 * Init actions
 *
 */
function sbst_init()
{
    //sbst_register_nav_menu() ;
    sbst_theme_widgets_init() ;
}

// Runs our code at the end to check that everything needed has loaded
add_action('init', 'sbst_init' );

/**
 * Facebook integration
 *
 */
function sbst_theme_facebook_connect()
{ 
    if (function_exists('fbc_is_configured') && fbc_is_configured())
    {
        if (is_user_logged_in())
        {
            fbc_display_login_state() ;
        }
        else
        {
            $user = wp_get_current_user();

            //  For the moment disallow connecting existing accounts
            if ($user->ID) return ;

            $button = render_fbconnect_button() ;
            echo "<li>$button</li>" ;

        }
    }
}

//  Hook in the Facebook integration
add_action('wp_meta', 'sbst_theme_facebook_connect');

/**
 * the_content filter - this filter adds support for
 * wp-print, wp-postviews, and a minimum height for the
 * .hentry class when a single post or page is displayed.
 *
 * @param string - content
 * @return string - filtered content
 */
function sbst_theme_the_content_filter($content)
{
    //  Define min-height for .hentry?

    if (is_single())
    {
?>
<style>
.hentry {
    min-height: 600px;
}
</style>
<?php
    }

    //  Support for wp-print
    if (function_exists('print_link'))
    {
        $content .= "<div class=\"print-link\">[print_link]</div><br style=\"clear: both;\" />" ;
    }

    //  Support for wp-postviews
    if(function_exists('the_views'))
    {
        $views = the_views(false) ;
        if (intval(post_custom('views')) == 1)
            $views = substr($views, 0, strlen($view) - 1) ;

        $content .= sprintf("<div class=\"post-views\">%s</div><br style=\"clear: both;\" />", $views) ;
    }

    return $content ;
}
add_filter('the_content', 'sbst_theme_the_content_filter') ;
?>
